/**
 * @file drv_12c.c
 * @brief 
 * 
 * @author dalin (dalin@open-robot.com)
 * @version 1.0
 * @date 2023-05-11
 * 
 * @copyright Copyright (c) 2023  Open Robot Tech.co, Ltd
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2023-05-11 <td>1.0     <td>dalin     <td>新建文件
 * <tr><td>2023-06-02 <td>1.1     <td>dalin     <td>添加阻塞的发送和接收
 * </table>
 */

#include "drv_i2c.h"

#ifdef USE_I2C_DRIVER
#include "i2c.h"

__weak I2C_HandleTypeDef hi2c1;
__weak I2C_HandleTypeDef hi2c2;
__weak I2C_HandleTypeDef hi2c3;


static I2C_HandleTypeDef* get_i2c_handle(i2cDrv_t drv)
{
    if(drv.hi2c == DRV_I2C1)
        return &hi2c1;
    else if(drv.hi2c == DRV_I2C2)
        return &hi2c2;
    else if(drv.hi2c == DRV_I2C3)
        return &hi2c3;
}


static int get_i2c_memsize(i2cDrv_t drv)
{
    if(drv.mem_size == DRV_I2C_MEMSIZE_8BIT)
        return I2C_MEMADD_SIZE_8BIT;
    else if(drv.mem_size == DRV_I2C_MEMSIZE_16BIT)
        return I2C_MEMADD_SIZE_16BIT;
}


/**
 * @brief 写I2C数据
 * 
 * @param  drv              : i2c结构体
 * @param  data             : 数据地址
 * @param  len              : 数据长度
 * @param  timeout          : 超时时间
 * 
 * @return int 
 */
int drv_i2c_send(i2cDrv_t drv, uint8_t * data, uint16_t len)
{
    I2C_HandleTypeDef *hi2c = get_i2c_handle(drv);
    int mem_size = get_i2c_memsize(drv);

    
    if(HAL_I2C_Mem_Write(hi2c, drv.dev_addr , drv.mem_addr , drv.mem_size, data, len, drv.timeout) != HAL_OK)
        return DRV_ERROR;
    else 
        return DRV_EOK;
}

/**
 * @brief 读取i2c数据
 * 
 * @param  drv              : i2c结构体
 * @param  data             : 数据地址
 * @param  len              : 数据长度
 * @param  timeout          : 超时时间
 * 
 * @return int 
 */
int  drv_i2c_recv(i2cDrv_t drv, uint8_t * data, uint16_t len)
{
    I2C_HandleTypeDef *hi2c = get_i2c_handle(drv);
    int mem_size = get_i2c_memsize(drv);
    
    if(HAL_I2C_Mem_Read(hi2c, drv.dev_addr , drv.mem_addr , drv.mem_size, data, len, drv.timeout) != HAL_OK)
        return DRV_ERROR;
    else 
        return DRV_EOK;   
}


/**
 * @brief 获取就绪的I2C总线设备
 * 
 * @param  drv              : i2c结构体
 * @param  trials           : 尝试次数
 * 
 * @return int 
 */
int drv_i2c_ready(i2cDrv_t drv, uint8_t trials)
{
    I2C_HandleTypeDef *hi2c = get_i2c_handle(drv);

    for(uint8_t i = 1; i < 255; i++)
	{
        if(HAL_I2C_IsDeviceReady(hi2c, drv.dev_addr, trials, drv.timeout) == HAL_OK)
        {
            return i;
        }  
    }
    return 0;
}


#endif /* USE_I2C_DRIVER */

